package com.umeox.ota.data.db;

import androidx.room.Database;
import androidx.room.RoomDatabase;

import java.util.List;

@Database(entities = ClientEntity.class, version = 2, exportSchema = false)
public abstract class ClientDb extends RoomDatabase {
    public static final String DB_NAME = ClientDb.class.getSimpleName();

    /**
     * 获取数据库
     *
     * @return ClientDao
     */
    public abstract ClientDao clientDao();

    public void setMid(String mid) {
        List<ClientEntity> clientEntities = clientDao().getAll();
        if (clientEntities == null || clientEntities.size() == 0) {
            ClientEntity clientEntity = new ClientEntity();
            clientEntity.setMid(mid);
            clientDao().insert(clientEntity);
        } else {
            clientDao().setMid(mid);
        }
        if (isOpen()) {
            close();
        }
    }

    public String queryMid() {
        String mid = clientDao().queryMid();
        if (isOpen()) {
            close();
        }
        return mid;
    }

    public void setDownloadTime(int i) {
        List<ClientEntity> clientEntities = clientDao().getAll();
        if ((null == clientEntities) || clientEntities.size() == 0) {
            ClientEntity clientEntity = new ClientEntity();
            clientEntity.setDownloadTime(i);
            clientDao().insert(clientEntity);
        } else {
            clientDao().setDownloadTime(i);
        }
        if (isOpen()) {
            close();
        }
    }

    public void increaseDownloadTime() {
        int i = clientDao().queryDownloadTime();
        setDownloadTime(++i);
    }

    public void resetDownloadTime() {
        setDownloadTime(0);
    }

    public int queryDownloadTime() {
        int i = clientDao().queryDownloadTime();
        if (isOpen()) {
            close();
        }
        return i;
    }

    /**
     * 设置 mid 获取次数
     *
     * @param i mid 获取次数
     */
    public void setObtainMidTime(int i) {
        List<ClientEntity> clientEntities = clientDao().getAll();
        if ((null == clientEntities) || clientEntities.size() == 0) {
            ClientEntity clientEntity = new ClientEntity();
            clientEntity.setObtainMidTime(i);
            clientDao().insert(clientEntity);
        } else {
            clientDao().setObtainMidTime(i);
        }
        if (isOpen()) {
            close();
        }
    }

    /**
     * mid 获取次数 +1
     */
    public void increaseObtainMidTime() {
        int i = clientDao().queryObtainMidTime();
        setObtainMidTime(++i);
    }

    /**
     * 重置 mid 获取次数为 0
     */
    public void resetObtainMidTime() {
        setObtainMidTime(0);
    }

    /**
     * @return 查询 mid 获取次数
     */
    public int queryObtainMidTime() {
        int i = clientDao().queryObtainMidTime();
        if (isOpen()) {
            close();
        }
        return i;
    }
}
